package com.koron.housing.apply.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.query.OrderItem;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.housing.admin.service.HousingAdminService;
import com.koron.housing.apply.bean.dto.HousingStaffApplyDTO;
import com.koron.housing.apply.bean.po.HousingStaffApply;
import com.koron.housing.apply.bean.po.HousingStaffIntegral;
import com.koron.housing.apply.bean.query.HousingApplyQuery;
import com.koron.housing.apply.bean.vo.HousingStaffApplyVO;
import com.koron.housing.apply.mapper.HousingStaffApplyMapper;
import com.koron.housing.apply.service.HousingStaffApplyService;
import com.koron.housing.apply.service.HousingStaffHonorService;
import com.koron.housing.apply.service.HousingStaffIntegralService;
import com.koron.housing.apply.service.HousingStaffRankService;
import com.koron.housing.staff.service.HousingStaffService;
import com.koron.housing.util.CodeUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 需求申请(HousingStaffApply)表服务实现类
 *
 * @author jzp
 * @since 2022-02-26 15:06:02
 */
@Service("applyService")
public class HousingStaffApplyServiceImpl implements HousingStaffApplyService {

    @Autowired
    private HousingStaffHonorService honorService;
    @Autowired
    private HousingStaffIntegralService integralService;
    @Autowired
    private HousingStaffRankService rankService;
    @Autowired
    private HousingAdminService adminService;
    @Autowired
    private HousingStaffService staffService;

    private String getCurrAccount() {
        return ThreadLocalContext.get().getAccount();
    }

    /**
     * 通过ID查询单条数据
     */
    @Override
    @TaskAnnotation("getById")
    public HousingStaffApply getById(SessionFactory factory, String id) {
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.selectById(id);
    }

    @Override
    @TaskAnnotation("getVoById")
    public HousingStaffApplyVO getVoById(SessionFactory factory, String id) {
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.selectVoById(id);
    }

    @Override
    @TaskAnnotation("getDtoById")
    public HousingStaffApplyDTO getDtoById(SessionFactory factory, String id) {
        HousingStaffApplyVO housingStaffApplyVO = getVoById(factory, id);
        HousingStaffApplyDTO housingStaffApplyDTO = BeanUtil.toBean(housingStaffApplyVO, HousingStaffApplyDTO.class);
        // 如果是公司自有，直接返回
        if ("0".equals(housingStaffApplyVO.getPropertySource())) {
            return housingStaffApplyDTO;
        }
        // 职称信息
        housingStaffApplyDTO.setRankList(rankService.listByApplyId(factory, id));
        // 工作荣誉
        housingStaffApplyDTO.setHonorList(honorService.listByApplyId(factory, id));
        // 积分信息
        housingStaffApplyDTO.setIntegral(integralService.getOneByApplyId(factory, id));
        return housingStaffApplyDTO;
    }

    /**
     * 查询所有数据
     */
    @Override
    @TaskAnnotation("list")
    public List<HousingStaffApplyVO> list(SessionFactory factory, HousingApplyQuery query) {
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.selectVoList(query);
    }

    @Override
    @TaskAnnotation("page")
    public PageInfo<HousingStaffApplyVO> page(SessionFactory factory, PageQuery pageQuery, HousingApplyQuery query) {
        // 如果不是过渡房管理员，需要setAccount
        if (!StringUtils.isEmpty(query.getHandler())) {
            query.setAccount(query.getHandler());
        }
        if (StringUtils.isEmpty(query.getAccount())) {
            boolean isAdmin = adminService.isAdmin(factory, getCurrAccount());
            query.setAccount(isAdmin ? null : getCurrAccount());
            query.setHandler(isAdmin ? null : getCurrAccount());
        }
        // 默认按总积分从高到低排
        if (CollectionUtils.isEmpty(pageQuery.getOrders())) {
            pageQuery.getOrders().add(new OrderItem("total", false));
        }
        pageQuery.unPrefixOrders("housingStaffApply", Arrays.asList("currNodeName", "currNodeUser", "total"));
        return HousingStaffApplyService.super.page(factory, pageQuery, query);
    }

    /**
     * 新增数据
     */
    @Override
    @TaskAnnotation("save")
    public boolean save(SessionFactory factory, HousingStaffApply housingStaffApply) {
        // 已入住租户不能再入住
        // HousingStaff byAccount = staffService.getByAccount(factory, getCurrAccount());
        /*if (byAccount != null && "1".equals(byAccount.getStatus())) {
            throw new IllegalStateException("租户记录中显示您已入住，请先退租");
        }*/

        if (StringUtils.isEmpty(housingStaffApply.getCode())) {
            housingStaffApply.setCode(CodeUtils.getApplyCode(housingStaffApply.getPropertySource()));
        }

        // 如果没有状态，则为草稿状态
        if (StringUtils.isEmpty(housingStaffApply.getStatus())) {
            housingStaffApply.setStatus("0");
        }
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.insertOrUpdate(housingStaffApply) > 0;
    }

    @Override
    @TaskAnnotation("saveDto")
    public boolean saveDto(SessionFactory factory, HousingStaffApplyDTO housingStaffApplyDTO) {
        Assert.hasText(housingStaffApplyDTO.getPropertySource(), "物业来源不能为空");
        // 1. 保存主体信息
        save(factory, housingStaffApplyDTO);

        // 2. 如果是公司自有租赁，直接返回
        if ("0".equals(housingStaffApplyDTO.getPropertySource())) {
            return true;
        }

        String applyId = housingStaffApplyDTO.getId();
        // 职称信息
        if (housingStaffApplyDTO.getRankList() != null) {
            rankService.removeByApplyId(factory, applyId);
            housingStaffApplyDTO.getRankList().forEach(e -> e.setApplyId(applyId));
            rankService.saveBatch(factory, housingStaffApplyDTO.getRankList());
        }

        // 工作荣誉
        if (housingStaffApplyDTO.getHonorList() != null) {
            honorService.removeByApplyId(factory, applyId);
            housingStaffApplyDTO.getHonorList().forEach(e -> e.setApplyId(applyId));
            honorService.saveBatch(factory, housingStaffApplyDTO.getHonorList());
        }

        // 积分信息
        if (housingStaffApplyDTO.getIntegral() != null) {
            integralService.removeByApplyId(factory, applyId);
            housingStaffApplyDTO.getIntegral().setApplyId(applyId);
            integralService.save(factory, housingStaffApplyDTO.getIntegral());
        }

        return true;
    }

    @Override
    @TaskAnnotation("saveIntegral")
    public boolean saveIntegral(SessionFactory factory, HousingStaffIntegral housingStaffIntegral) {
        // 积分信息
        return integralService.save(factory, housingStaffIntegral);
    }

    @Override
    @TaskAnnotation("end")
    public boolean end(SessionFactory factory, String id) {
        // 原有入住申请单归档
        HousingStaffApply source = getById(factory, id);

        HousingApplyQuery applyQuery = new HousingApplyQuery();
        applyQuery.setAccount(source.getAccount());
        applyQuery.setStatus(Collections.singletonList("2"));
        List<HousingStaffApplyVO> list = list(factory, applyQuery);
        for (HousingStaffApplyVO housingStaffApplyVO : list) {
            updateStatus(factory, housingStaffApplyVO.getId(), "3");
        }

        // 未入住：需求申请审批通过后，未成功办理入住（未审批完成）的人员
        updateStatus(factory, id, "2");
        // 更新租户和房源信息
        return staffService.notInto(factory, getDtoById(factory, id));
    }

    /**
     * 点提交。需要计算积分信息
     */
    @Override
    @TaskAnnotation("submit")
    public boolean submit(SessionFactory factory, String id) {
        updateStatus(factory, id, "1");
        HousingStaffApplyDTO apply = getDtoById(factory, id);
        // 2. 如果是公司自有租赁，直接返回
        if ("0".equals(apply.getPropertySource())) {
            return true;
        }
        apply.computeIntegral();
        return saveIntegral(factory, apply.getIntegral());
    }

    /**
     * 修改数据
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, HousingStaffApply housingStaffApply) {
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.update(housingStaffApply) > 0;
    }

    @Override
    @TaskAnnotation("updateStatus")
    public boolean updateStatus(SessionFactory factory, String id, String status) {
        HousingStaffApply housingStaffApply = new HousingStaffApply();
        housingStaffApply.setId(id);
        housingStaffApply.setStatus(status);
        return update(factory, housingStaffApply);
    }

    /**
     * 通过主键删除数据
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        HousingStaffApplyMapper mapper = factory.getMapper(HousingStaffApplyMapper.class);
        return mapper.hidden(id) > 0;
    }
}
